package com.auto.survey.activity.monitoring.entity.ctrlmeasure

import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.auto.survey.activity.monitoring.entity.MonitoringObject
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.activity.monitoring.entity.MonitoringStation
import com.auto.survey.util.Helper

/**
 * 闭合观测序列数据类，表示一个A-B-A的观测路径
 */

@Entity(
    tableName = "ClosedLoopObservation",
    foreignKeys = [
        ForeignKey(
            entity = MonitoringObject::class,
            parentColumns = ["id"],
            childColumns = ["monitoringObjectId"],
            onDelete = ForeignKey.CASCADE
        ),
        ForeignKey(
            entity = MonitoringStation::class,
            parentColumns = ["id"],
            childColumns = ["stationId"],
            onDelete = ForeignKey.CASCADE
        ),
        // 确保起点和终点引用有效测点
        ForeignKey(
            entity = MonitoringPoint::class,
            parentColumns = ["id"],
            childColumns = ["startPointId"],
            onDelete = ForeignKey.RESTRICT // 防止删除正在被引用的测点
        ),
        ForeignKey(
            entity = MonitoringPoint::class,
            parentColumns = ["id"],
            childColumns = ["endPointId"],
            onDelete = ForeignKey.RESTRICT
        )
    ],
    indices = [
        Index(value = ["monitoringObjectId"]),
        Index(value = ["stationId"]),
        Index(value = ["startPointId"]),
        Index(value = ["endPointId"]),
        // 复合索引，加速按对象和状态的查询
        Index(value = ["monitoringObjectId", "status"])
    ]
)
data class ClosedLoopObservation(
    /**
     * 序列ID，主键，自增长
     */
    @PrimaryKey(autoGenerate = true) val id: Int = 0,

    /**
     * 所属监测对象ID
     */
    val monitoringObjectId: Int,

    /**
     * 所属站点ID
     */
    val stationId: Int,

    /**
     * 闭合序列名称
     */
    val loopName: String,

    /**
     * 起点ID (对应MonitoringPoint的id)
     */
    var startPointId: Int?,

    /**
     * 终点ID (理论上应与起点ID相同)
     */
    var endPointId: Int?,

    /**
     * 创建时间
     */
    val createTime: String = Helper.formatTimestamp(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"),

    /**
     * 完成时间
     */
    var completeTime: String? = null,

    /**
     * 序列状态：0-进行中，1-已完成，2-已验证，3-验证失败
     */
    var status: Int = 0
)
